//authController.js
const bcrypt = require('bcrypt');
const User = require('../models/userModel');
const jwt = require('jsonwebtoken');
const { ethers } = require('ethers');


// 注册
exports.register = async (req, res) => {
  try {
    const { username, password, email, phone, points_balance, role } = req.body;

    if (!password || password.trim() === '') {
      return res.status(400).json({ message: '密码不能为空' });
    }

    // 生成钱包地址和私钥
    const wallet = ethers.Wallet.createRandom();
    const walletAddress = wallet.address;
    const privateKey = wallet.privateKey;
    const mnemonic = wallet.mnemonic.phrase;
    // 打印助记词，确认是否正确生成
    console.log('Generated Mnemonic:', mnemonic);
    

    // 使用 bcrypt 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 将用户信息存入数据库，不存储私钥
    await User.create({
      username,
      password: hashedPassword,
      email,
      phone,
      points_balance: points_balance || 0.00,
      role: role || '普通用户',
      wallet_address: walletAddress
    });

    // 返回钱包地址和私钥信息（供用户保存）
    res.status(201).json({
      message: '注册成功！请妥善保存您的私钥。',
      wallet_address: walletAddress,
      privateKey: privateKey,
      mnemonic: mnemonic
    });
  } catch (error) {
    console.error('Registration error:', error);
    res.status(500).json({ message: '注册失败', error: error.message });
  }

};
// 登录
exports.login = async (req, res) => { 
  try {
    const { email, password } = req.body;

    // 查询用户
    const user = await User.findByEmail(email);
    if (!user) {
      return res.status(400).json({ message: '用户名或密码错误' });
    }

    // 比较密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return res.status(400).json({ message: '用户名或密码错误' });
    }

    // 密码匹配，生成 JWT token
    const token = jwt.sign(
      { id: user.user_id, role: user.role, email: user.email, username: user.username },
      process.env.JWT_SECRET,
      { expiresIn: '1h' }
    );

    // 返回 token 和钱包地址
    res.json({ token, walletAddress: user.wallet_address,role:user.role ,message: '登录成功' });

  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ message: '登录失败' });
  }
};

